<?php
/**
 *RechargeConfigServices
 * @author tan bing
 * @date 2021-09-18 10:36
 */


namespace Modules\Recharge\Services\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Modules\Recharge\Entities\RechargeSetting;
use Modules\Recharge\Enums\SettingEnum;

class RechargeConfigServices extends BaseService
{

    /**
     * @var Request
     * @author tan bing
     */
    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取指定的配置项
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @author tan bing
     * @date 2021-09-18 10:38
     */
    public function getRechargeConfig()
    {
        $result = RechargeSetting::where('key', SettingEnum::RECHARGE)->first();
        if(!$result) $result = RechargeSetting::getDefaultData();
        else {
            $result = $result->values;
        }
        !empty($result['bg_image']) && $result['thumb_bg_image'] = URL::asset('') . $result['bg_image'];
        !empty($result['ad_image']) && $result['thumb_ad_image'] = URL::asset('') . $result['ad_image'];
        !empty($result['recharge_describe_icon']) && $result['thumb_recharge_describe_icon'] = URL::asset('') . $result['recharge_describe_icon'];

        return $result;
    }

    /**
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @author tan bing
     * @date 2021-09-18 10:42
     */
    public function saveRechargeConfig()
    {
        $data = $this->request->post();
        try {
            if(isset($data['form']['file'])) unset($data['form']['file']);
            $result = (new RechargeSetting())->saveSetting($data['key'], $data['form']);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $result;
    }
}